var connection = require('./connection');

function getHot() {
    let sql = 'select a.*,c.title as category_title from article a inner join hot b inner join category c on a.id=b.id and a.category_id=c.id order by modify_time desc';
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }

        })
    });
}

function getCate() {
    let sql = 'select * from category order by modify_time desc';
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }

        })
    });
}

function getCateById(id) {
    let sql = 'select * from category where id="' + id + '"';
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }

        })
    });
}

/**
 * 根据类别获取文章列表
 * @param category_id
 */
function getArticleListByCate(category_id) {
    let sql = 'select a.*,IF(ISNULL(B.ID),false,true) AS "isHot" from article a left join hot b on a.id=b.id where a.category_id="' + category_id + '" order by modify_time desc';
    if (!category_id) {
        // 获取所有文章列表
        sql = 'select a.*,IF(ISNULL(B.ID),false,true) AS "isHot" from article a left join hot b on a.id=b.id order by modify_time desc';
    }
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, res) {
            if (err) {
                console.log(err)
                reject(err);
            } else {
                resolve(res);
            }
        })
    });
}

function getArticleById(id) {
    let sql = 'select * from article where id="' + id + '" order by modify_time desc';
    return new Promise(function(resolve, reject) {
        connection.query(sql, function(err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }
        })
    });
}

module.exports = {
    getHot: getHot,
    getCate: getCate,
    getCateById: getCateById,
    getArticleListByCate: getArticleListByCate,
    getArticleById: getArticleById
}
